import numpy as np
import cv2

COMM = None
frame = None
try:
  import serial
  COMM = serial.Serial('/dev/ttyAMA0', 115200, timeout=0.5)
except ImportError:
  print('error occured when import serial')

def make_a_photo(event,x,y,flags,param):
  if event == cv2.EVENT_LBUTTONDBLCLK:
    cv2.imwrite('photo.jpg', frame)

cv2.namedWindow('frame')
cv2.setMouseCallback('frame',make_a_photo)

def start():
  global frame
  cap = cv2.VideoCapture(0)

  while(1):
    # Take each frame
    _, frame = cap.read()
    blur = cv2.GaussianBlur(frame, (21, 21), 0)
    # Convert BGR to HSV
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower = np.array([20,50,50])
    upper = np.array([40,255,255])
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")
    mask = cv2.inRange(hsv, lower, upper)

    # Bitwise-AND mask and original image
    fire_img = cv2.bitwise_and(frame,hsv, mask= mask)

    gray = cv2.cvtColor(fire_img,cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
    image, contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    if len(contours) > 0:
      write_to_serial('1')
    for c in contours:
      (x, y, w, h) = cv2.boundingRect(c)
      cv2.rectangle(frame, (x-5, y-5), (x + 5 + w, y+5 + h), (0, 0, 255), 2)
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  cap.release()
  cv2.destroyAllWindows()

def write_to_serial(flag):
  if COMM is not None and COMM.isOpen():
    COMM.write(flag.encode())

if __name__ == '__main__':
  start()